import { defineStore } from "pinia";
import msgpack from "msgpack-lite";
import { Config } from "@common/config";

interface IImgSrcObj {
  [key: string]: string;
}

interface ICenterObj {
  [key: string]: {
    position: number[];
    color: {
      h_color: string;
      v_color: string;
    };
    mip: {
      delta_x: number;
      delta_y: number;
    };
  };
}

interface IExtraInfo {
  [key: string]: {
    px_per_mm: number;
    window_width: number;
    window_center: number;
  };
}



const useImageDataStore = defineStore("imageData", {
  state: () => {
    return {
      imgSrcObj: {} as IImgSrcObj,
      fourCornelObj: {},
      sliceInfoObj: {},
      mprCenterObj: {} as ICenterObj,
      extraInfoObj: {} as IExtraInfo,
    };
  },
  actions: {
    updateImageData(data) {
      console.log("收到img");
      // 解析图像的耗时约1ms
      if (Config.img_transfer_mode === "base64") {
        this.handleBase64(data);
      } else if (Config.img_transfer_mode === "binary") {
        this.handleBinary(data);
      }
    },
    handleBase64(data) {
      if (data.msgType === "img") {
        for (const [viewId, content] of Object.entries(data.content) as [
          string,
          any,
        ]) {
          if (content.img) {
            this.imgSrcObj[viewId] = `${content.img}`;
          }
          this.resolveMsg(viewId, content);
        }
      }
    },
    handleBinary(data) {
      const uintData = new Uint8Array(data);
      const deocodeData = msgpack.decode(uintData, {
        codec: msgpack.createCodec({
          binaryType: "uint8array",
        }),
      });
      if (deocodeData.msgType === "img") {
        for (const [viewId, content] of Object.entries(deocodeData.content) as [
          string,
          any,
        ]) {
          if (content.img) {
            const blob = new Blob([content.img], { type: "image/jpeg" });
            this.imgSrcObj[viewId] = URL.createObjectURL(blob);
          }
          this.resolveMsg(viewId, content);
        }
      }
    },
    resolveMsg(viewId,content){
      if (content.info_layer) {
        this.fourCornelObj[viewId] = content.info_layer;
      }
      if (content.slice_info) {
        this.sliceInfoObj[viewId] = content.slice_info;
      }
      if (content.extra_info) {
        this.extraInfoObj[viewId] = content.extra_info;
      }
      if (content.center) {
        console.log(
          `收到的mip信息为：${JSON.stringify(content.center.mip)}`,
        );
        this.mprCenterObj[viewId] = content.center;
      }
    },
    clearImgData(viewId) {
      if (this.imgSrcObj[viewId]) {
        this.imgSrcObj[viewId] = "";
      }
    },
    clearCrossLine(viewId) {
      if (this.mprCenterObj[viewId]) {
        delete this.mprCenterObj[viewId];
      }
    },
    clearPercentRule(viewId) {
      if (this.extraInfoObj[viewId] && this.extraInfoObj[viewId].px_per_mm) {
        this.extraInfoObj[viewId].px_per_mm = 0;
      }
    },
  },
});

export { useImageDataStore };
